#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
主机表格模型模块 - 为表格视图提供数据模型
"""

import logging
from typing import Dict, List, Any
from PyQt5.QtCore import QAbstractTableModel, QModelIndex
from PyQt5.QtCore import Qt  # 直接导入Qt类
from PyQt5.QtGui import QColor

# 定义Qt常量的整数值
class QtConst:
    DisplayRole = 0
    UserRole = 32
    BackgroundRole = 8
    Horizontal = 1
    NoItemFlags = 0
    ItemIsEnabled = 1
    ItemIsSelectable = 2

logger = logging.getLogger(__name__)

class HostTableModel(QAbstractTableModel):
    """主机表格数据模型"""
    
    def __init__(self, hosts: List[Dict[str, Any]], parent=None, ip_cache=None, port_cache=None):
        """
        初始化主机表格模型
        
        Args:
            hosts (List[Dict[str, Any]]): 主机列表
            parent: 父对象
            ip_cache: IP地址缓存字典
            port_cache: 端口号缓存字典
        """
        super().__init__(parent)
        self.hosts = hosts
        self.headers = ["主机群组id", "IP地址", "主机名称", "可见名称", "状态", "端口号"]
        self.ip_cache = ip_cache or {}  # 如果没有提供缓存，使用空字典
        self.port_cache = port_cache or {}  # 如果没有提供端口缓存，使用空字典
    
    def rowCount(self, parent=QModelIndex()):
        """返回行数"""
        return len(self.hosts)
    
    def columnCount(self, parent=QModelIndex()):
        """返回列数"""
        return len(self.headers)
    
    def data(self, index, role=Qt.DisplayRole):
        """
        返回数据
        
        Args:
            index: 索引
            role: 角色
            
        Returns:
            数据值
        """
        if not index.isValid() or not (0 <= index.row() < len(self.hosts)):
            return None
        
        host = self.hosts[index.row()]
        
        if role == Qt.DisplayRole:
            if index.column() == 0:
                # 主机群组ID列
                return host.get("group_id", "")
            elif index.column() == 1:
                # IP地址列 - 使用缓存数据
                hostid = host.get("hostid", "")
                if hostid in self.ip_cache:
                    return ", ".join(self.ip_cache[hostid])
                return ""
            elif index.column() == 2:
                # 主机名称列(技术名称) - host字段
                return host.get("host", "")
            elif index.column() == 3:
                # 可见名称列 - name字段
                return host.get("name", "")
            elif index.column() == 4:
                # 状态列
                status = int(host.get("status", "0"))
                return "已启用" if status == 0 else "已禁用"
            elif index.column() == 5:
                # 端口号列 - 从主机接口获取
                hostid = host.get("hostid", "")
                if hostid in self.port_cache:
                    return ", ".join(self.port_cache[hostid])
                # 如果缓存中没有，检查主机中是否直接有端口信息
                if "port" in host:
                    return host["port"]
                return ""
        
        elif role == Qt.UserRole:
            # 返回主机ID，无论是哪一列被查询
            return host.get("hostid", "")
        
        elif role == Qt.BackgroundRole:
            # 设置禁用状态的背景色
            if index.column() == 4:  # 状态列
                status = int(host.get("status", "0"))
                if status != 0:
                    return QColor(255, 200, 200)  # 浅红色背景表示禁用状态
            
            # 如果技术名称为空，设置该行背景色为浅黄色，提示需要注意
            if index.column() == 2 and not host.get("host"):
                return QColor(255, 255, 200)  # 浅黄色背景表示缺少技术名称
                
            # 根据端口号设置不同的背景色
            if index.column() == 5:  # 端口号列
                # 获取端口值
                port_value = ""
                hostid = host.get("hostid", "")
                if hostid in self.port_cache:
                    ports = self.port_cache[hostid]
                    if ports and len(ports) > 0:
                        port_value = ports[0]  # 使用第一个端口值
                elif "port" in host:
                    port_value = host["port"]
                
                # 根据端口号设置背景色
                if port_value == "10050":
                    return QColor(230, 255, 230)  # 淡绿色 - Zabbix Agent
                elif port_value == "161":
                    return QColor(230, 230, 255)  # 淡蓝色 - SNMP
        
        return None
    
    def headerData(self, section, orientation, role=Qt.DisplayRole):
        """
        返回表头数据
        
        Args:
            section: 段索引
            orientation: 方向
            role: 角色
            
        Returns:
            表头数据
        """
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            if 0 <= section < len(self.headers):
                return self.headers[section]
        
        return None
    
    def flags(self, index):
        """
        返回项标志
        
        Args:
            index: 索引
            
        Returns:
            项标志
        """
        if not index.isValid():
            return Qt.NoItemFlags
        
        return Qt.ItemIsEnabled | Qt.ItemIsSelectable 